Micron Document
<!DOCTYPE html>
<html class="client-nojs vector-feature-night-mode-disabled vector-feature-language-in-header-enabled vector-feature-language-in-main-page-header-disabled vector-feature-page-tools-pinned-disabled vector-feature-toc-pinned-clientpref-1 vector-feature-main-menu-pinned-disabled vector-feature-limited-width-clientpref-1 vector-feature-limited-width-content-enabled vector-feature-custom-font-size-clientpref-1 vector-feature-appearance-pinned-clientpref-1 vector-sticky-header-enabled" lang="en" dir="ltr"><head>
<meta charset="UTF-8">
<title>Resource management (computing)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="https://en.wikipedia.org/wiki/Resource_management_(computing)"> <link href="./mw/ext.cite.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/ext.pygments.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.icons.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.search.codex.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/user.styles.css" rel="stylesheet" type="text/css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" type="text/css" href="./mw/site.styles.css">
<link rel="stylesheet" type="text/css" href="./mw/noscript.css">
<link rel="stylesheet" type="text/css" href="./footer.css">
<link rel="stylesheet" type="text/css" href="./vector-2022.css">
</head>
<body class="skin--responsive skin-vector skin-vector-search-vue mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Resource_management_computing rootpage-Resource_management_computing skin-vector-2022 action-view">
<div class="mw-page-container">
<div class="mw-page-container-inner">
<div class="mw-content-container">
<main id="content" class="mw-body">
<header class="mw-body-header vector-page-titlebar">
<h1 id="firstHeading" class="firstHeading mw-first-heading">
<span id="openzim-page-title" class="mw-page-title-main"><span class="mw-page-title-main">Resource management (computing)</span></span>
</h1>
</header>
<a id="top"></a>
<div id="bodyContent" class="vector-body ve-init-mw-desktopArticleTarget-targetContainer" aria-labelledby="firstHeading" data-mw-ve-target-container="">
<div id="mw-content-text" class="mw-body-content mw-content-ltr" lang="en" dir="ltr"><div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr">
<p>In <a href="Computer_programming" title="Computer programming">computer programming</a>, <b>resource management</b> refers to techniques for managing <a href="System_resource" title="System resource">resources</a> (components with limited availability).
</p><p><a href="Computer_program" title="Computer program">Computer programs</a> may manage their own resources by using features exposed by <a href="Programming_language" title="Programming language">programming languages</a> (<a href="#CITEREFElderJacksonLiblit2008">Elder, Jackson &amp; Liblit (2008)</a> is a survey article contrasting different approaches), or may elect to manage them by a host – an <a href="Operating_system" title="Operating system">operating system</a> or <a href="Virtual_machine" title="Virtual machine">virtual machine</a> – or another program.
</p><p>Host-based management is known as <i>resource tracking,</i> and consists of cleaning up resource leaks: terminating access to resources that have been acquired but not released after use. This is known as <i>reclaiming</i> resources, and is analogous to <a href="Garbage_collection_(computer_science)" title="Garbage collection (computer science)">garbage collection</a> for memory. On many systems, the operating system reclaims resources after the process makes the <a href="Exit_(system_call)" title="Exit (system call)">exit</a> <a href="System_call" title="System call">system call</a>.
</p>
<meta property="mw:PageProp/toc">
<div class="mw-heading mw-heading2"><h2 id="Controlling_access">Controlling access</h2></div>
<p>The omission of releasing a resource when a program has finished using it is known as a <a href="Resource_leak" title="Resource leak">resource leak</a>, and is an issue in sequential computing. Multiple processes wish to access a limited resource can be an issue in <a href="Concurrent_computing" title="Concurrent computing">concurrent computing</a>, and is known as <a href="Resource_contention" title="Resource contention">resource contention</a>.
</p><p>Resource management seeks to control access in order to prevent both of these situations.
</p>
<div class="mw-heading mw-heading3"><h3 id="Resource_leak">Resource leak</h3></div>
<style data-mw-deduplicate="TemplateStyles:r1236090951">
/* start https://en.wikipedia.org/ */


.mw-parser-output .hatnote{font-style:italic}.mw-parser-output div.hatnote{padding-left:1.6em;margin-bottom:0.5em}.mw-parser-output .hatnote i{font-style:normal}.mw-parser-output .hatnote+link+.hatnote{margin-top:-0.5em}@media print{body.ns-0 .mw-parser-output .hatnote{display:none!important}}


/* end https://en.wikipedia.org/ */
</style><div role="note" class="hatnote navigation-not-searchable">Main article: <a href="Resource_leak" title="Resource leak">resource leak</a></div>
<p>Formally, resource management (preventing resource leaks) consists of ensuring that a resource is released if and only if it is successfully acquired. This general problem can be abstracted as "<i>before,</i> <i>body,</i> and <i>after</i>" code, which normally are executed in this order, with the condition that the <i>after</i> code is called if and only if the <i>before</i> code successfully completes, regardless of whether the <i>body</i> code executes successfully or not. This is also known as <i>execute around</i><sup id="cite_ref-FOOTNOTEBeck199737–39_1-0" class="reference"><a href="#cite_note-FOOTNOTEBeck199737–39-1"><span class="cite-bracket">[</span>1<span class="cite-bracket">]</span></a></sup> or a <i>code sandwich,</i> and occurs in various other contexts,<sup id="cite_ref-FOOTNOTEElderJacksonLiblit20083_2-0" class="reference"><a href="#cite_note-FOOTNOTEElderJacksonLiblit20083-2"><span class="cite-bracket">[</span>2<span class="cite-bracket">]</span></a></sup> such as a temporary change of program state, or <a href="Tracing_(software)" title="Tracing (software)">tracing</a> entry and exit into a <a href="Subroutine" class="mw-redirect" title="Subroutine">subroutine</a>. However, resource management is the most commonly cited application. In <a href="Aspect-oriented_programming" title="Aspect-oriented programming">aspect-oriented programming</a>, such execute around logic is a form of <i><a href="Advice_(programming)" title="Advice (programming)">advice</a></i>.
</p><p>In the terminology of <a href="Control_flow_analysis" class="mw-redirect" title="Control flow analysis">control flow analysis</a>, resource release must <a href="Postdominate" class="mw-redirect" title="Postdominate">postdominate</a> successful resource acquisition;<sup id="cite_ref-FOOTNOTEElderJacksonLiblit20082_3-0" class="reference"><a href="#cite_note-FOOTNOTEElderJacksonLiblit20082-3"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup> failure to ensure this is a bug, and a code path that violates this condition causes a resource leak. Resource leaks are often minor problems, generally not crashing the program, but instead causing some slowdown to the program or the overall system.<sup id="cite_ref-FOOTNOTEElderJacksonLiblit20083_2-1" class="reference"><a href="#cite_note-FOOTNOTEElderJacksonLiblit20083-2"><span class="cite-bracket">[</span>2<span class="cite-bracket">]</span></a></sup> However, they may cause crashes – either the program itself or other programs – due to <i>resource exhaustion:</i> if the system runs out of resources, acquisition requests fail. This can present a <a href="Security_bug" title="Security bug">security bug</a> if an attack can cause resource exhaustion. Resource leaks may happen under regular program flow – such as simply forgetting to release a resource – or only in exceptional circumstances, such as when a resource is not released if there is an exception in another part of the program. Resource leaks are very frequently caused by <a href="Structured_programming#Early_exit" title="Structured programming">early exit</a> from a subroutine, either by a <code>return</code> statement, or an exception raised either by the subroutine itself, or a deeper subroutine that it calls. While resource release due to return statements can be handled by carefully releasing within the subroutine before the return, exceptions cannot be handled without some additional language facility that guarantees that release code is executed.
</p><p>More subtly, successful resource acquisition must <a href="Dominator_(graph_theory)" title="Dominator (graph theory)">dominate</a> resource release, as otherwise the code will try to release a resource it has not acquired. The consequences of such an incorrect release range from being silently ignored to crashing the program or unpredictable behavior. These bugs generally manifest rarely, as they require resource allocation to first fail, which is generally an exceptional case. Further, the consequences may not be serious, as the program may already be crashing due to failure to acquire an essential resource. However, these can prevent recovery from the failure, or turn an orderly shutdown into a disorderly shutdown. This condition is generally ensured by first checking that the resource was successfully acquired before releasing it, either by having a boolean variable to record "successfully acquired" – which lacks atomicity if the resource is acquired but the flag variable fails to be updated, or conversely – or by the handle to the resource being a <a href="Nullable_type" title="Nullable type">nullable type</a>, where "null" indicates "not successfully acquired", which ensures atomicity.
</p>
<div class="mw-heading mw-heading3"><h3 id="Resource_contention">Resource contention</h3></div>
<div role="note" class="hatnote navigation-not-searchable">Main article: <a href="Resource_contention" title="Resource contention">resource contention</a></div>
<p>In computer science, <a rel="nofollow" class="external text" href="https://www.techtarget.com/whatis/definition/resource-contention">resource contention</a> refers to a conflict that arises when multiple entities attempt to access a shared resource, like random access memory, disk storage, cache memory, internal buses, or external network devices.
</p>
<div class="mw-heading mw-heading2"><h2 id="Memory_management">Memory management</h2></div>
<div role="note" class="hatnote navigation-not-searchable">Main article: <a href="Memory_management" title="Memory management">Memory management</a></div>
<p>Memory can be treated as a resource, but <a href="Memory_management" title="Memory management">memory management</a> is usually considered separately, primarily because memory allocation and deallocation is significantly more frequent than acquisition and release of other resources, such as file handles. Memory managed by an <i>external</i> system has similarities to both (internal) memory management (since it is memory) and resource management (since it is managed by an external system). Examples include memory managed via native code and used from Java (via <a href="Java_Native_Interface" title="Java Native Interface">Java Native Interface</a>); and objects in the <a href="Document_Object_Model" title="Document Object Model">Document Object Model</a> (DOM), used from <a href="JavaScript" title="JavaScript">JavaScript</a>. In both these cases, the <a href="Memory_management" title="Memory management">memory manager</a> (<a href="Garbage_collection_(computer_science)" title="Garbage collection (computer science)">garbage collector</a>) of the <a href="Runtime_environment" class="mw-redirect" title="Runtime environment">runtime environment</a> (virtual machine) is unable to manage the external memory (there is no shared memory management), and thus the external memory is treated as a resource, and managed analogously. However, cycles between systems (JavaScript referring to the DOM, referring back to JavaScript) can make management difficult or impossible.
</p>
<div class="mw-heading mw-heading2"><h2 id="Lexical_management_and_explicit_management">Lexical management and explicit management</h2></div>
<p>A key distinction in resource management within a program is between <i>lexical management</i> and <i>explicit management</i> – whether a resource can be handled as having a lexical scope, such as a stack variable (lifetime is restricted to a single lexical scope, being acquired on entry to or within a particular scope, and released when execution exits that scope), or whether a resource must be explicitly allocated and released, such as a resource acquired within a function and then returned from it, which must then be released outside of the acquiring function. Lexical management, when applicable, allows a better separation of concerns and is less error-prone.
</p>
<div class="mw-heading mw-heading2"><h2 id="Basic_techniques">Basic techniques</h2></div>
<p>The basic approach to resource management is to acquire a resource, do something with it, then release it, yielding code of the form (illustrated with opening a file in <a href="Python_(programming_language)" title="Python (programming language)">Python</a>):
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
<p>This is correct if the intervening <code>...</code> code does not contain an early exit (<code>return</code>), the language does not have exceptions, and <code>open</code> is guaranteed to succeed. However, it causes a resource leak if there is a return or exception, and causes an incorrect release of unacquired resource if <code>open</code> can fail.
</p><p>There are two more fundamental problems: the acquisition-release pair is not adjacent (the release code must be written far from the acquisition code), and resource management is not encapsulated – the programmer must manually ensure that they are always paired. In combination, these mean that acquisition and release must be explicitly paired, but cannot be placed together, thus making it easy for these to not be paired correctly.
</p><p>The resource leak can be resolved in languages that support a <code>finally</code> construction (like Python) by placing the body in a <code>try</code> clause, and the release in a <code>finally</code> clause:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">finally</span><span class="p">:</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
<p>This ensures correct release even if there is a return within the body or an exception thrown. Further, note that the acquisition occurs <i>before</i> the <code>try</code> clause, ensuring that the <code>finally</code> clause is only executed if the <code>open</code> code succeeds (without throwing an exception), assuming that "no exception" means "success" (as is the case for <code>open</code> in Python). If resource acquisition can fail without throwing an exception, such as by returning a form of <code>null</code>, it must also be checked before release, such as:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">finally</span><span class="p">:</span>
<span class="k">if</span> <span class="n">f</span><span class="p">:</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
<p>While this ensures correct resource management, it fails to provide adjacency or encapsulation. In many languages there are mechanisms that provide encapsulation, such as the <code>with</code> statement in Python:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="o">...</span>
</pre></div>
<p>The above techniques – unwind protection (<code>finally</code>) and some form of encapsulation – are the most common approach to resource management, found in various forms in <a href="C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a>, <a href="Common_Lisp" title="Common Lisp">Common Lisp</a>, <a href="Java_(programming_language)" title="Java (programming language)">Java</a>, <a href="Python_(programming_language)" title="Python (programming language)">Python</a>, <a href="Ruby_(programming_language)" title="Ruby (programming language)">Ruby</a>, <a href="Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a>, and <a href="Smalltalk" title="Smalltalk">Smalltalk</a>,<sup id="cite_ref-FOOTNOTEBeck199737–39_1-1" class="reference"><a href="#cite_note-FOOTNOTEBeck199737–39-1"><span class="cite-bracket">[</span>1<span class="cite-bracket">]</span></a></sup> among others; they date to the late 1970s in the <a href="NIL_(programming_language)" title="NIL (programming language)">NIL</a> dialect of Lisp; see <a href="Exception_handling#History" title="Exception handling">Exception handling §&nbsp;History</a>. There are many variations in the implementation, and there are also significantly different <a href="#Approaches">approaches</a>.
</p>
<div class="mw-heading mw-heading2"><h2 id="Approaches">Approaches</h2></div>
<div class="mw-heading mw-heading3"><h3 id="Unwind_protection">Unwind protection</h3></div>
<p>The most common approach to resource management across languages is to use unwind protection, which is called when execution exits a scope – by execution running off the end of the block, returning from within the block, or an exception being thrown. This works for stack-managed resources, and is implemented in many languages, including C#, Common Lisp, Java, Python, Ruby, and Scheme. The main problems with this approach is that the release code (most commonly in a <code>finally</code> clause) may be very distant from the acquisition code (it lacks <i>adjacency</i>), and that the acquisition and release code must always be paired by the caller (it lacks <i>encapsulation</i>). These can be remedied either functionally, by using closures/callbacks/coroutines (Common Lisp, Ruby, Scheme), or by using an object that handles both the acquisition and release, and adding a language construct to call these methods when control enters and exits a scope (C# <code>using</code>, Java <code>try</code>-with-resources, Python <code>with</code>); see below.
</p><p>An alternative, more imperative approach, is to write asynchronous code in <a href="Direct_style" class="mw-redirect" title="Direct style">direct style</a>: acquire a resource, and then in the next line have a <i>deferred</i> release, which is called when the scope is exited – synchronous acquisition followed by asynchronous release. This originated in C++ as the ScopeGuard class, by <a href="Andrei_Alexandrescu" title="Andrei Alexandrescu">Andrei Alexandrescu</a> and Petru Marginean in 2000,
<sup id="cite_ref-4" class="reference"><a href="#cite_note-4"><span class="cite-bracket">[</span>4<span class="cite-bracket">]</span></a></sup> with improvements by Joshua Lehrer,<sup id="cite_ref-5" class="reference"><a href="#cite_note-5"><span class="cite-bracket">[</span>5<span class="cite-bracket">]</span></a></sup> and has direct language support in D via the <code>scope</code> keyword (<a rel="nofollow" class="external text" href="http://dlang.org/statement.html#ScopeGuardStatement">ScopeGuardStatement</a>), where it is one approach to <a href="Exception_safety" title="Exception safety">exception safety</a>, in addition to RAII (see below).<sup id="cite_ref-6" class="reference"><a href="#cite_note-6"><span class="cite-bracket">[</span>6<span class="cite-bracket">]</span></a></sup> It has also been included in Go, as the <code><a rel="nofollow" class="external text" href="https://golang.org/ref/spec#Defer_statements">defer</a></code> statement.<sup id="cite_ref-7" class="reference"><a href="#cite_note-7"><span class="cite-bracket">[</span>7<span class="cite-bracket">]</span></a></sup> This approach lacks encapsulation – one must explicitly match acquisition and release – but avoids having to create an object for each resource (code-wise, avoid writing a class for each type of resource).
</p>
<div class="mw-heading mw-heading3"><h3 id="Object-oriented_programming">Object-oriented programming</h3></div>
<p>In <a href="Object-oriented_programming" title="Object-oriented programming">object-oriented programming</a>, resources are encapsulated within objects that use them, such as a <code>file</code> object having a <a href="Field_(computer_science)" title="Field (computer science)">field</a> whose value is a <a href="File_descriptor" title="File descriptor">file descriptor</a> (or more general <a href="File_handle" class="mw-redirect" title="File handle">file handle</a>). This allows the object to use and manage the resource without users of the object needing to do so. However, there is a wide variety of ways that objects and resources can be related.
</p><p>Firstly, there is the question of ownership: does an object <i>have</i> a resource?
</p>
<ul><li>Objects can <i>own</i> resources (via <a href="Object_composition" title="Object composition">object composition</a>, a strong "has a" relationship).</li>
<li>Objects can <i>view</i> resources (via <a href="Object_aggregation" class="mw-redirect" title="Object aggregation">object aggregation</a>, a weak "has a" relationship).</li>
<li>Objects can <i>communicate</i> with other objects that have resources (via <a href="Association_(object-oriented_programming)" title="Association (object-oriented programming)">Association</a>).</li></ul>
<p>Objects that have a resource can acquire and release it in different ways, at different points during the <a href="Object_lifetime" title="Object lifetime">object lifetime</a>; these occur in pairs, but in practice they are often not used symmetrically (see below):
</p>
<ul><li>Acquire/release while the object is valid, via (instance) methods such as <code>open</code> or <code>dispose</code>.</li>
<li>Acquire/release during object creation/destruction (in the initializer and finalizer).</li>
<li>Neither acquire nor release the resource, instead simply having a <i>view</i> or <i>reference</i> to a resource managed externally to the object, as in <a href="Dependency_injection" title="Dependency injection">dependency injection</a>; concretely, an object that has a resource (or can communicate with one that does) is passed in as an argument to a method or constructor.</li></ul>
<p>Most common is to acquire a resource during object creation, and then explicitly release it via an instance method, commonly called <code>dispose</code>. This is analogous to traditional file management (acquire during <code>open</code>, release by explicit <code>close</code>), and is known as the <a href="Dispose_pattern" title="Dispose pattern">dispose pattern</a>. This is the basic approach used in several major modern object-oriented languages, including <a href="Java_(programming_language)" title="Java (programming language)">Java</a>, <a href="C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a> and <a href="Python_(programming_language)" title="Python (programming language)">Python</a>, and these languages have additional constructs to automate resource management. However, even in these languages, more complex object relationships result in more complex resource management, as discussed below.
</p>
<div class="mw-heading mw-heading4"><h4 id="RAII">RAII</h4></div>
<div role="note" class="hatnote navigation-not-searchable">Main article: <a href="Resource_Acquisition_Is_Initialization" class="mw-redirect" title="Resource Acquisition Is Initialization">Resource Acquisition Is Initialization</a></div>
<p>A natural approach is to make holding a resource be a <a href="Class_invariant" title="Class invariant">class invariant</a>: resources are acquired during object creation (specifically initialization), and released during object destruction (specifically finalization). This is known as <a href="Resource_Acquisition_Is_Initialization" class="mw-redirect" title="Resource Acquisition Is Initialization">Resource Acquisition Is Initialization</a> (RAII), and ties resource management to <a href="Object_lifetime" title="Object lifetime">object lifetime</a>, ensuring that live objects have all necessary resources. Other approaches do not make holding the resource a class invariant, and thus objects may not have necessary resources (because they've not been acquired yet, have already been released, or are being managed externally), resulting in errors such as trying to read from a closed file. This approach ties resource management to memory management (specifically object management), so if there are no memory leaks (no object leaks), there are no <a href="Resource_leak" title="Resource leak">resource leaks</a>. RAII works naturally for heap-managed resources, not only stack-managed resources, and is composable: resources held by objects in arbitrarily complicated relationships (a complicated <a href="Object_graph" title="Object graph">object graph</a>) are released transparently simply by object destruction (so long as this is done properly!).
</p><p>RAII is the standard resource management approach in C++, but is little-used outside C++, despite its appeal, because it works poorly with modern automatic memory management, specifically <a href="Tracing_garbage_collection" title="Tracing garbage collection">tracing garbage collection</a>: RAII <i>ties</i> resource management to memory management, but these have significant differences. Firstly, because resources are expensive, it is desirable to release them promptly, so objects holding resources should be destroyed as soon as they become garbage (are no longer in use). Object destruction is prompt in deterministic memory management, such as in C++ (stack-allocated objects are destroyed on stack unwind, heap-allocated objects are destroyed manually via calling <code>delete</code> or automatically using <code>unique_ptr</code>) or in deterministic reference-counting (where objects are destroyed immediately when their reference count falls to 0), and thus RAII works well in these situations. However, most modern automatic memory management is non-deterministic, making no guarantees that objects will be destroyed promptly or even at all! This is because it is cheaper to leave some garbage allocated than to precisely collect each object immediately on its becoming garbage. Secondly, releasing resources during object destruction means that an object must have a <i><a href="Finalizer" title="Finalizer">finalizer</a></i> (in deterministic memory management known as a <i>destructor</i>) – the object cannot simply be deallocated – which significantly complicates and slows garbage collection.
</p>
<div class="mw-heading mw-heading4"><h4 id="Complex_relationships">Complex relationships</h4></div>
<p>When multiple objects rely on a single resource, resource management can be complicated.
</p><p>A fundamental question is whether a "has a" relationship is one of <i>owning</i> another object (<a href="Object_composition" title="Object composition">object composition</a>), or <i>viewing</i> another object (<a href="Object_aggregation" class="mw-redirect" title="Object aggregation">object aggregation</a>). A common case is when one two objects are chained, as in <a href="Pipe_and_filter" class="mw-redirect" title="Pipe and filter">pipe and filter</a> pattern, the <a href="Delegation_pattern" title="Delegation pattern">delegation pattern</a>, the <a href="Decorator_pattern" title="Decorator pattern">decorator pattern</a>, or the <a href="Adapter_pattern" title="Adapter pattern">adapter pattern</a>. If the second object (which is not used directly) holds a resource, is the first object (which is used directly) responsible for managing the resource? This is generally answered identically to whether the first object <i>owns</i> the second object: if so, then the owning object is also responsible for resource management ("having a resource" is <a href="Transitive_relation" title="Transitive relation">transitive</a>), while if not, then it is not. Further, a single object may "have" several other objects, owning some and viewing others.
</p><p>Both cases are commonly found, and conventions differ. Having objects that use resources indirectly be responsible for the resource (composition) provides <a href="Encapsulation_(computer_programming)" title="Encapsulation (computer programming)">encapsulation</a> (one only needs the object that clients use, without separate objects for the resources), but results in considerable complexity, particularly when a resource is shared by multiple objects or objects have complex relationships. If only the object that directly uses the resource is responsible for the resource (aggregation), relationships between other objects that use the resources can be ignored, but there is no encapsulation (beyond the directly using object): the resource must be managed directly, and might not be available to the indirectly using object (if it has been released separately).
</p><p>Implementation-wise, in object composition, if using the dispose pattern, the owning object thus will also have a <code>dispose</code> method, which in turn calls the <code>dispose</code> methods of owned objects that must be disposed; in RAII this is handled automatically (so long as owned objects are themselves automatically destroyed: in C++ if they are a value or a <code>unique_ptr</code>, but not a raw pointer: see pointer ownership). In object aggregation, nothing needs to be done by the viewing object, as it is not responsible for the resource.
</p><p>Both are commonly found. For example, in the <a href="Java_Class_Library" title="Java Class Library">Java Class Library</a>, <code><a rel="nofollow" class="external text" href="https://docs.oracle.com/javase/8/docs/api/java/io/Reader.html#close--">Reader#close()</a></code> closes the underlying stream, and these can be chained. For example, a <code><a rel="nofollow" class="external text" href="https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html">BufferedReader</a></code> may contain a <code><a rel="nofollow" class="external text" href="https://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html">InputStreamReader</a></code>, which in turn contains a <code><a rel="nofollow" class="external text" href="https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html">FileInputStream</a></code>, and calling <code>close</code> on the <code>BufferedReader</code> in turn closes the <code>InputStreamReader</code>, which in turn closes the <code>FileInputStream</code>, which in turn releases the system file resource. Indeed, the object that directly uses the resource can even be anonymous, thanks to encapsulation:
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="k">try</span><span class="w"> </span><span class="p">(</span><span class="n">BufferedReader</span><span class="w"> </span><span class="n">reader</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">BufferedReader</span><span class="p">(</span><span class="k">new</span><span class="w"> </span><span class="n">InputStreamReader</span><span class="p">(</span><span class="k">new</span><span class="w"> </span><span class="n">FileInputStream</span><span class="p">(</span><span class="n">fileName</span><span class="p">))))</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// Use reader.</span>
<span class="p">}</span>
<span class="c1">// reader is closed when the try-with-resources block is exited, which closes each of the contained objects in sequence.</span>
</pre></div>
<p>However, it is also possible to manage only the object that directly uses the resource, and not use resource management on wrapper objects:
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="k">try</span><span class="w"> </span><span class="p">(</span><span class="n">FileInputStream</span><span class="w"> </span><span class="n">stream</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">FileInputStream</span><span class="p">(</span><span class="n">fileName</span><span class="p">))))</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">BufferedReader</span><span class="w"> </span><span class="n">reader</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">BufferedReader</span><span class="p">(</span><span class="k">new</span><span class="w"> </span><span class="n">InputStreamReader</span><span class="p">(</span><span class="n">stream</span><span class="p">));</span>
<span class="w"> </span><span class="c1">// Use reader.</span>
<span class="p">}</span>
<span class="c1">// stream is closed when the try-with-resources block is exited.</span>
<span class="c1">// reader is no longer usable after stream is closed, but so long as it does not escape the block, this is not a problem.</span>
</pre></div>
<p>By contrast, in Python, a <a rel="nofollow" class="external text" href="https://docs.python.org/3/library/csv.html#csv.reader">csv.reader</a> does not own the <code>file</code> that it is reading, so there is no need (and it is not possible) to close the reader, and instead the <code>file</code> itself must be closed.<sup id="cite_ref-8" class="reference"><a href="#cite_note-8"><span class="cite-bracket">[</span>8<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="c1"># Use r.</span>
<span class="c1"># f is closed when the with-statement is exited, and can no longer be used.</span>
<span class="c1"># Nothing is done to r, but the underlying f is closed, so r cannot be used either.</span>
</pre></div>
<p>In <a href=".NET_Framework" title=".NET Framework">.NET</a>, convention is to only have direct user of resources be responsible: "You should implement IDisposable only if your type uses unmanaged resources directly."<sup id="cite_ref-idisposable_9-0" class="reference"><a href="#cite_note-idisposable-9"><span class="cite-bracket">[</span>9<span class="cite-bracket">]</span></a></sup>
</p><p>In case of a more complicated <a href="Object_graph" title="Object graph">object graph</a>, such as multiple objects sharing a resource, or cycles between objects that hold resources, proper resource management can be quite complicated, and exactly the same issues arise as in object finalization (via destructors or finalizers); for example, the <a href="Lapsed_listener_problem" title="Lapsed listener problem">lapsed listener problem</a> can occur and cause resource leaks if using the
<a href="Observer_pattern" title="Observer pattern">observer pattern</a> (and observers hold resources). Various mechanisms exist to allow greater control of resource management. For example, in the <a href="Google_Closure_Library" class="mw-redirect" title="Google Closure Library">Google Closure Library</a>, the <code><a rel="nofollow" class="external text" href="https://closure-library.googlecode.com/git-history/docs/class_goog_Disposable.html">goog.Disposable</a></code> class provides a <code>registerDisposable</code> method to register other objects to be disposed with this object, together with various lower-level instance and class methods to manage disposal.
</p>
<div class="mw-heading mw-heading3"><h3 id="Structured_programming">Structured programming</h3></div>
<p>In <a href="Structured_programming" title="Structured programming">structured programming</a>, stack resource management is done simply by nesting code sufficiently to handle all cases. This requires only a single return at the end of the code, and can result in heavily nested code if many resources must be acquired, which is considered an <a href="Anti-pattern" title="Anti-pattern">anti-pattern</a> by some – the <i><a rel="nofollow" class="external text" href="http://c2.com/cgi/wiki?ArrowAntiPattern">Arrow Anti Pattern</a>,</i><sup id="cite_ref-10" class="reference"><a href="#cite_note-10"><span class="cite-bracket">[</span>10<span class="cite-bracket">]</span></a></sup> due to the triangular shape from the successive nesting.
</p>
<div class="mw-heading mw-heading3"><h3 id="Cleanup_clause">Cleanup clause</h3></div>
<p>One other approach, which allows early return but consolidates cleanup in one place, is to have a single exit return of a function, preceded by cleanup code, and to use <a href="Goto" title="Goto">goto</a> to jump to the cleanup before exit. This is infrequently seen in modern code, but occurs in some uses of C.
</p>
<div class="mw-heading mw-heading2"><h2 id="See_also">See also</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1266661725">
/* start https://en.wikipedia.org/ */


.mw-parser-output .portalbox{padding:0;margin:0.5em 0;display:table;box-sizing:border-box;max-width:175px;list-style:none}.mw-parser-output .portalborder{border:1px solid var(--border-color-base,#a2a9b1);padding:0.1em;background:var(--background-color-neutral-subtle,#f8f9fa)}.mw-parser-output .portalbox-entry{display:table-row;font-size:85%;line-height:110%;height:1.9em;font-style:italic;font-weight:bold}.mw-parser-output .portalbox-image{display:table-cell;padding:0.2em;vertical-align:middle;text-align:center}.mw-parser-output .portalbox-link{display:table-cell;padding:0.2em 0.2em 0.2em 0.3em;vertical-align:middle}@media(min-width:720px){.mw-parser-output .portalleft{margin:0.5em 1em 0.5em 0}.mw-parser-output .portalright{clear:right;float:right;margin:0.5em 0 0.5em 1em}}


/* end https://en.wikipedia.org/ */
</style>
<ul><li><a href="Memory_management" title="Memory management">Memory management</a></li>
<li><a href="Pool_(computer_science)" title="Pool (computer science)">Pool (computer science)</a></li></ul>
<div class="mw-heading mw-heading2"><h2 id="References">References</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1239543626">
/* start https://en.wikipedia.org/ */


.mw-parser-output .reflist{margin-bottom:0.5em;list-style-type:decimal}@media screen{.mw-parser-output .reflist{font-size:90%}}.mw-parser-output .reflist .references{font-size:100%;margin-bottom:0;list-style-type:inherit}.mw-parser-output .reflist-columns-2{column-width:30em}.mw-parser-output .reflist-columns-3{column-width:25em}.mw-parser-output .reflist-columns{margin-top:0.3em}.mw-parser-output .reflist-columns ol{margin-top:0}.mw-parser-output .reflist-columns li{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .reflist-upper-alpha{list-style-type:upper-alpha}.mw-parser-output .reflist-upper-roman{list-style-type:upper-roman}.mw-parser-output .reflist-lower-alpha{list-style-type:lower-alpha}.mw-parser-output .reflist-lower-greek{list-style-type:lower-greek}.mw-parser-output .reflist-lower-roman{list-style-type:lower-roman}


/* end https://en.wikipedia.org/ */
</style><div class="reflist">
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-FOOTNOTEBeck199737–39-1"><span class="mw-cite-backlink">^ <a href="#cite_ref-FOOTNOTEBeck199737–39_1-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-FOOTNOTEBeck199737–39_1-1"><sup><i><b>b</b></i></sup></a></span> <span class="reference-text"><a href="#CITEREFBeck1997">Beck 1997</a>, pp.&nbsp;37–39.</span>
</li>
<li id="cite_note-FOOTNOTEElderJacksonLiblit20083-2"><span class="mw-cite-backlink">^ <a href="#cite_ref-FOOTNOTEElderJacksonLiblit20083_2-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-FOOTNOTEElderJacksonLiblit20083_2-1"><sup><i><b>b</b></i></sup></a></span> <span class="reference-text"><a href="#CITEREFElderJacksonLiblit2008">Elder, Jackson &amp; Liblit 2008</a>, p.&nbsp;3.</span>
</li>
<li id="cite_note-FOOTNOTEElderJacksonLiblit20082-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-FOOTNOTEElderJacksonLiblit20082_3-0">^</a></b></span> <span class="reference-text"><a href="#CITEREFElderJacksonLiblit2008">Elder, Jackson &amp; Liblit 2008</a>, p.&nbsp;2.</span>
</li>
<li id="cite_note-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-4">^</a></b></span> <span class="reference-text">"<a rel="nofollow" class="external text" href="http://www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758">Generic: Change the Way You Write Exception-Safe Code — Forever</a>", by <a href="Andrei_Alexandrescu" title="Andrei Alexandrescu">Andrei Alexandrescu</a> and Petru Marginean, December 01, 2000, <i>Dr. Dobb's</i></span>
</li>
<li id="cite_note-5"><span class="mw-cite-backlink"><b><a href="#cite_ref-5">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://jlehrer.privatedns.org:8000/scopeguard.html">ScopeGuard 2.0</a>, Joshua Lehrer</span>
</li>
<li id="cite_note-6"><span class="mw-cite-backlink"><b><a href="#cite_ref-6">^</a></b></span> <span class="reference-text">D: <a rel="nofollow" class="external text" href="http://dlang.org/exception-safe.html">Exception Safety</a></span>
</li>
<li id="cite_note-7"><span class="mw-cite-backlink"><b><a href="#cite_ref-7">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="https://blog.golang.org/defer-panic-and-recover">Defer, Panic, and Recover</a>, Andrew Gerrand, <i>The Go Blog,</i> 4 August 2010</span>
</li>
<li id="cite_note-8"><span class="mw-cite-backlink"><b><a href="#cite_ref-8">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="https://stackoverflow.com/questions/3216954/python-no-csv-close">Python: No csv.close()?</a></span>
</li>
<li id="cite_note-idisposable-9"><span class="mw-cite-backlink"><b><a href="#cite_ref-idisposable_9-0">^</a></b></span> <span class="reference-text"><style data-mw-deduplicate="TemplateStyles:r1238218222">
/* start https://en.wikipedia.org/ */


.mw-parser-output cite.citation{font-style:inherit;word-wrap:break-word}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation:target{background-color:rgba(0,127,255,0.133)}.mw-parser-output .id-lock-free.id-lock-free a{background:url("./mw/Lock-green.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited.id-lock-limited a,.mw-parser-output .id-lock-registration.id-lock-registration a{background:url("./mw/Lock-gray-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription.id-lock-subscription a{background:url("./mw/Lock-red-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-ws-icon a{background:url("./mw/Wikisource-logo.svg")right 0.1em center/12px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-free a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-limited a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-registration a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-subscription a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .cs1-ws-icon a{background-size:contain;padding:0 1em 0 0}.mw-parser-output .cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;color:var(--color-error,#d33)}.mw-parser-output .cs1-visible-error{color:var(--color-error,#d33)}.mw-parser-output .cs1-maint{display:none;color:#085;margin-left:0.3em}.mw-parser-output .cs1-kern-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}@media screen{.mw-parser-output .cs1-format{font-size:95%}html.skin-theme-clientpref-night .mw-parser-output .cs1-maint{color:#18911f}}@media screen and (prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .cs1-maint{color:#18911f}}


/* end https://en.wikipedia.org/ */
</style><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://msdn.microsoft.com/en-us/library/system.idisposable(v=vs.110).aspx">"IDisposable Interface"</a><span class="reference-accessdate">. Retrieved <span class="nowrap">2016-04-03</span></span>.</cite></span>
</li>
<li id="cite_note-10"><span class="mw-cite-backlink"><b><a href="#cite_ref-10">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://blog.codinghorror.com/flattening-arrow-code/">Flattening Arrow Code</a>, Jeff Atwood, 10 Jan 2006</span>
</li>
</ol></div></div>
<style data-mw-deduplicate="TemplateStyles:r1239549316">
/* start https://en.wikipedia.org/ */


.mw-parser-output .refbegin{margin-bottom:0.5em}.mw-parser-output .refbegin-hanging-indents>ul{margin-left:0}.mw-parser-output .refbegin-hanging-indents>ul>li{margin-left:0;padding-left:3.2em;text-indent:-3.2em}.mw-parser-output .refbegin-hanging-indents ul,.mw-parser-output .refbegin-hanging-indents ul li{list-style:none}@media(max-width:720px){.mw-parser-output .refbegin-hanging-indents>ul>li{padding-left:1.6em;text-indent:-1.6em}}.mw-parser-output .refbegin-columns{margin-top:0.3em}.mw-parser-output .refbegin-columns ul{margin-top:0}.mw-parser-output .refbegin-columns li{page-break-inside:avoid;break-inside:avoid-column}@media screen{.mw-parser-output .refbegin{font-size:90%}}


/* end https://en.wikipedia.org/ */
</style><div class="refbegin" style="">
<ul><li><cite id="CITEREFBeck1997" class="citation book cs1"><a href="Kent_Beck" title="Kent Beck">Beck, Kent</a> (1997). <i>Smalltalk Best Practice Patterns</i>. Prentice Hall. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a>&nbsp;<bdi>978-0134769042</bdi>.</cite></li>
<li><cite id="CITEREFElderJacksonLiblit2008" class="citation techreport cs1">Elder, Matt; Jackson, Steve; Liblit, Ben (October 2008). <a rel="nofollow" class="external text" href="http://research.cs.wisc.edu/techreports/2008/TR1647.pdf"><i>Code Sandwiches</i></a> <span class="cs1-format">(PDF)</span> (Technical report). <a href="University_of_Wisconsin%E2%80%93Madison" title="University of Wisconsin–Madison">University of Wisconsin–Madison</a>. 1647, <a rel="nofollow" class="external text" href="http://pages.cs.wisc.edu/~liblit/tr-1647/">abstract</a></cite> <span class="cs1-visible-error citation-comment"><code class="cs1-code">{{cite tech report}}</code>: </span><span class="cs1-visible-error citation-comment">External link in <code class="cs1-code"><code class="cs1-code">|postscript=</code></code> (help)</span><span class="cs1-maint citation-comment">CS1 maint: postscript (link)</span></li></ul>
</div>
<div class="mw-heading mw-heading2"><h2 id="Further_reading">Further reading</h2></div>
<ul><li><a rel="nofollow" class="external text" href="http://joeduffyblog.com/2005/04/08/dg-update-dispose-finalization-and-resource-management/">DG Update: Dispose, Finalization, and Resource Management</a>, <a href="Joe_Duffy" title="Joe Duffy">Joe Duffy</a></li></ul>
<div class="mw-heading mw-heading2"><h2 id="External_links">External links</h2></div>
<ul><li><a rel="nofollow" class="external text" href="http://c2.com/cgi/wiki?DeterministicResourceManagement">Deterministic Resource Management</a>, <i><a href="WikiWikiWeb" title="WikiWikiWeb">WikiWikiWeb</a></i></li></ul></div><!--htdig_noindex--><div><div class="zim-footer">
This article is issued from <a class="external text" title="Last edited on 2025-07-24" href="https://en.wikipedia.org/wiki/?title=Resource_management_(computing)&amp;oldid=1302250405">Wikipedia</a>. The text is available under <a class="external text" href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons Attribution-Share Alike 4.0</a> unless otherwise noted. Additional terms may apply for the media files.
</div>
</div><!--/htdig_noindex--></div>
</div>
</main>
</div>
</div>
</div>

</body></html>